using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;

public class MaterialReplaceWindow : EditorWindow
{
    [MenuItem("PresenceTools/材质球替换")]
    private static void OpenWindow()
    {
        GetWindow<MaterialReplaceWindow>();
    }

    private GameObject sourceGo;
    private GameObject targetGo;

    private void OnGUI()
    {
        SkinnProCustomUtility.DrawColorLabel("\t\t\t请选择场景内的不是蓝色的GameObject", Color.yellow);
        GUILayout.Space(10);

        sourceGo = EditorGUILayout.ObjectField("Source (unity/xx.fbx): ", sourceGo, typeof(GameObject)) as GameObject;
        GUILayout.Space(10);

        targetGo = EditorGUILayout.ObjectField("Target (maya/xx.fbx): ", targetGo, typeof(GameObject)) as GameObject;
        GUILayout.Space(10);

        if (sourceGo && !SkinnProCustomUtility.IsNotPrefab(sourceGo))
        {
            sourceGo = null;

            return;
        }

        if (targetGo && !SkinnProCustomUtility.IsNotPrefab(targetGo))
        {
            targetGo = null;

            return;
        }

        if (GUILayout.Button("替换"))
        {
            ReplaceMats();
        }
    }

    private void ReplaceMats()
    {
        var sourceChilds = sourceGo.GetComponentsInChildren<Renderer>();
        var targetChilds = targetGo.GetComponentsInChildren<Renderer>();

        if (sourceChilds.Length != targetChilds.Length)
        {
            Debug.Log("请检查两个角色是否结构不一致？");

            return;
        }

        for (int i = 0; i < sourceChilds.Length; i++)
        {
            var sourceMesh = sourceChilds[i];
            var targetMesh = targetChilds[i];

            var sourceMats = sourceMesh.sharedMaterials;
            var targetMats = targetMesh.sharedMaterials;
            if (sourceMats.Length != targetMats.Length)
            {
                Debug.Log("请检查两个角色是否结构不一致？");

                return;
            }

            for (int j = 0; j < sourceMats.Length; j++)
            {
                targetMats[j] = sourceMats[j];
                Debug.Log(string.Format("{0}  ----  {1}", sourceMats[j].name, targetMats[j].name));
            }

            targetMesh.sharedMaterials = sourceMesh.sharedMaterials;
        }
    }
}
